package com.bz.xtcx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.enums.CheckStatusEnum;
import com.bz.xtcx.manager.enums.UserTypeEnum;
import com.bz.xtcx.manager.mapper.*;
import com.bz.xtcx.manager.service.ILibImageService;
import com.bz.xtcx.manager.service.ILibService;
import com.bz.xtcx.manager.service.IResCodeCreater;
import com.bz.xtcx.manager.utils.ExcelUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoQuery;
import com.bz.xtcx.manager.vo.VoResponse;
import com.bz.xtcx.manager.vo.VoTaskSum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LibService extends BaseService implements ILibService {
    /** 日志. */
    private final Logger logger = LoggerFactory.getLogger(LibService.class);

    @Autowired
    private LibEnterpriseMapper libEnterpriseMapper;
    
    @Autowired
    private LibServiceMapper libServiceMapper;
    
    @Autowired
    private LibCollegeMapper libCollegeMapper;
    
    @Autowired
    private LibExpertMapper libExpertMapper;
    
    @Autowired
    private BusUserFormHisMapper busUserFormHisMapper;
    
    @Autowired
    private BusUserFormMapper busUserFormMapper;
    
    @Autowired
    private BusUserMapper busUserMapper;
    
    @Autowired
    private LibReqMapper libReqMapper;
    
    @Autowired
    private LibResMapper libResMapper;
    
    @Autowired
    private BusUserCheckMapper busUserCheckMapper;
    
    @Autowired
    private ILibImageService libImageService;
    
    @Autowired
    private IResCodeCreater resCodeCreater;

    @Autowired
    private DataStatisticsMapper dataStatisticsMapper;

    @Value("${file.tomcatAddr}")
    private String tomcatAddr;

    @Value("${file.tomcatPath}")
    private String tomcatPath;

    @Override
    public BusUserForm getUserForm(int type) {
        BusUserForm from = busUserFormMapper.findByType(type);
        return from;
    }

    @Override
    public VoResponse setUserForm(BusUserForm form) {
        VoResponse voRes = new VoResponse();
        if(StringUtils.isEmpty(form.getId())) {
            //BusUserForm from = busUserFormMapper.findByType(form.getFormType());
        }
        form.setCreater(getUserName());
        busUserFormMapper.insert(form);
        return voRes;
    }
    
    @Override
    public BusUser getUserDetailById(String userId) {
        BusUser user = busUserMapper.findById(userId);
        if(user != null) {
            user.setPassword(null);
            BusUserForm form = busUserFormHisMapper.findByUserId(userId);
            user.setForm(form);
        }
        return user;
    }
    
    @Override
    public VoResponse getUserDetail(boolean isDraft) {
        VoResponse voRes = new VoResponse();
        User user = this.getUser();
        if (null == user) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或已超时，请重新登录");
            return voRes;
        }
        BusUserForm form = null;
        if(isDraft) {
            form = busUserFormHisMapper.findByUserIdAndCheck(user.getUserType(), user.getUserId(), -1);
            if(form != null) {
                voRes.setData(form);
                return voRes;
//                return form;
            }
        }
        form = busUserFormHisMapper.findByUserId(user.getUserId());
        if (null != form) {
            voRes.setData(form);
            return voRes;
        }
        voRes.setFail(voRes);
        voRes.setMessage("获得上报信息失败");
        return voRes;
//        return form;
    }
    
    boolean setResCode(BusUserForm form, String prefix) {
        String resCode = null;
        try {
            resCode = resCodeCreater.makeResCode(prefix);
            form.setNumber(resCode);
            return true;
        } catch (XtcxException e) {
            e.printStackTrace();
        }
        return false;
    }
    
    @Override
    public VoResponse setUserDetail(String detail) {
        VoResponse voRes = new VoResponse();
        JSONObject json = null;
        try {
            json = JSON.parseObject(detail);
        }catch (Exception e) {
            logger.error("解析资源库数据异常", e);
            voRes.setFail(voRes);
            voRes.setMessage("解析资源库数据异常");
            return voRes;
        }
        int result = 0;
        User user = this.getUser();
        BusUserForm form = busUserFormHisMapper.findByUserId(user.getUserId());
        if(form == null) {
            form = new BusUserForm();
            form.setFormType(user.getUserType());
            if(!this.setResCode(form, UserTypeEnum.getTheCode(form.getFormType()))) {
                voRes.setFail(voRes);
                voRes.setMessage("获取编码异常");
                return voRes;
            }
            // TODO:
            BusUser userModel = null;
            if (!StringUtils.isEmpty(form.getName()) && !StringUtils.isEmpty(form.getCode())) {
                userModel = busUserMapper.findByNameAndCode(form.getName(), form.getCode());
            }
            if (userModel != null) {
                form.setUserId(userModel.getId());//发布人id
            } else {
                form.setUserId(user.getUserId());//发布人id
            }
            form.setCreater(user.getUserName());
            form.setName(json.getString("name"));
            form.setCode(json.getString("code"));
        }else {
            if (WzStrUtil.isBlank(form.getNumber())) {
                if(!this.setResCode(form, UserTypeEnum.getTheCode(form.getFormType()))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("获取编码异常");
                    return voRes;
                }
            }
            if (WzStrUtil.isBlank(form.getUserId())) {
                form.setUserId(user.getUserId());
            }
            if (WzStrUtil.isBlank(form.getCreater())) {
                form.setCreater(user.getUserName());
            }
            form.setUpdater(user.getUserName());
        }
        form.setCheckStatus(0);

        // 将编辑的name和code 复制到 alias中
        form.setNameAlias(json.getString("name"));
        form.setCodeAlias(json.getString("code"));

//        form.setDetail(detail);
        boolean isWrongUser = false;
        if (WzStrUtil.isNotBlank(form.getName()) && !form.getName().equals(json.getString("name"))) {
            isWrongUser = true;
        }
        if (WzStrUtil.isNotBlank(form.getCode()) && !form.getCode().equals(json.getString("code"))) {
            isWrongUser = true;
        }
//        if (isWrongUser) {
//            voRes.setFail(voRes);
//            voRes.setMessage("录入的名称和证件号须与账号的名称和证件号一致");
//            return voRes;
//        }


        voRes = this.vaiidate(form, json);
        if(!voRes.getSuccess()) {
            return voRes;
        }
        // 修改图片
        if (WzStrUtil.isNotBlank(json.getString("picLogo"))) {
            try {
                json.put("picLogo", getImageName(json,"picLogo"));
            } catch (Exception ex) {
                json.put("picLogo", json.getString("picLogo"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picOrgLicense"))) {
            try {
                json.put("picOrgLicense", getImageName(json,"picOrgLicense"));
            } catch (Exception ex) {
                json.put("picOrgLicense", json.getString("picOrgLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpLicense"))) {
            try {
                json.put("picLpLicense", getImageName(json,"picLpLicense"));
            } catch (Exception ex) {
                json.put("picLpLicense", json.getString("picLpLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardFront"))) {
            try {
                json.put("picLpIdCardFront", getImageName(json,"picLpIdCardFront"));
            } catch (Exception ex) {
                json.put("picLpIdCardFront", json.getString("picLpIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardBack"))) {
            try {
                json.put("picLpIdCardBack", getImageName(json,"picLpIdCardBack"));
            } catch (Exception ex) {
                json.put("picLpIdCardBack", json.getString("picLpIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardInHand"))) {
            try {
                json.put("picLpIdCardInHand", getImageName(json,"picLpIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLpIdCardInHand", json.getString("picLpIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardFront"))) {
            try {
                json.put("picLmIdCardFront", getImageName(json,"picLmIdCardFront"));
            } catch (Exception ex) {
                json.put("picLmIdCardFront", json.getString("picLmIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardBack"))) {
            try {
                json.put("picLmIdCardBack", getImageName(json,"picLmIdCardBack"));
            } catch (Exception ex) {
                json.put("picLmIdCardBack", json.getString("picLmIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardInHand"))) {
            try {
                json.put("picLmIdCardInHand", getImageName(json,"picLmIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLmIdCardInHand", json.getString("picLmIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picCommitmentLetter"))) {
            try {
                json.put("picCommitmentLetter", getImageName(json,"picCommitmentLetter"));
            } catch (Exception ex) {
                json.put("picCommitmentLetter", json.getString("picCommitmentLetter"));
            }
        }
        form.setDetail(JSONObject.toJSONString(json));
        result = this.saveOrUpdate(form);
        if(result <= 0) {
            voRes.setFail(voRes);
            return voRes;
        }
        return voRes;
    }
    
    @Override
    @Transactional
    public VoResponse addLib(BusUserForm form) {
        VoResponse voRes = new VoResponse();
        User user = this.getUser();
        if (null == user) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或已超时，请重新登录");
            return voRes;
        }
        if(user.getUserType() != 0) {
            if(form.getCheckStatus() > 0) {
                form.setCheckStatus(0);
            }
        }
        JSONObject json = null;
        try {
            json = JSON.parseObject(form.getDetail());
        }catch (Exception e) {
            e.printStackTrace();
            voRes.setFail(voRes);
            voRes.setMessage("表格数据异常");
            return voRes;
        }
        
        int result = 0;
        if(WzStrUtil.isBlank(form.getId())) {
            //新增判断重复数据
            List<BusUserForm> list = null;
            if(form.getFormType() == 6 || form.getFormType() == 7) {
                String reName = json.getString("re_name");
                if(!StringUtils.isEmpty(reName)) {
                    list = busUserFormHisMapper.findByReName(reName);
                    if(list != null && list.size() > 0) {
                        voRes.setFail(voRes);
                        voRes.setMessage("名称已经存在");
                        return voRes;
                    }
                }
            }else {
                if(!StringUtils.isEmpty(json.getString("code"))) {
                    list = busUserFormHisMapper.findByCodeAndType(json.getString("code"), form.getFormType());
                    if(list != null && list.size() > 0) {
                        voRes.setFail(voRes);
                        voRes.setMessage("代码已经存在");
                        return voRes;
                    }
                }
            }
            if(!this.setResCode(form, UserTypeEnum.getTheCode(form.getFormType()))) {
                voRes.setFail(voRes);
                voRes.setMessage("获取编码异常");
                return voRes;
            }
            // TODO:
            BusUser userModel = null;
            if (!StringUtils.isEmpty(form.getName()) && !StringUtils.isEmpty(form.getCode())) {
                userModel = busUserMapper.findByNameAndCode(form.getName(), form.getCode());
            }
            if (userModel != null) {
                form.setUserId(userModel.getId());//发布人id
            } else {
                form.setUserId(user.getUserId());//发布人id
            }
            form.setCreater(user.getUserName());
            form.setName(json.getString("name"));
            form.setCode(json.getString("code"));
        } else {
            BusUserForm old = busUserFormHisMapper.findById(form.getId());
            if(old == null) {
                voRes.setFail(voRes);
                voRes.setMessage("获取资源数据异常");
                return voRes;
            }
            if(old.getCheckStatus() == 0) {
                voRes.setFail(voRes);
                voRes.setMessage("待审状态不能编辑");
                return voRes;
            }
            if (WzStrUtil.isBlank(form.getNumber())) {
                if(!this.setResCode(form, UserTypeEnum.getTheCode(form.getFormType()))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("获取编码异常");
                    return voRes;
                }
            }
            // TODO:
            BusUser userModel = null;
            if (!StringUtils.isEmpty(form.getName()) && !StringUtils.isEmpty(form.getCode())) {
                userModel = busUserMapper.findByNameAndCode(form.getName(), form.getCode());
            }
            if (userModel != null) {
                form.setUserId(userModel.getId());//发布人id
            } else {
                form.setUserId(user.getUserId());//发布人id
            }
            form.setCreater(user.getUserName());
            form.setUpdater(user.getUserName());
            form.setName(old.getName());
            form.setCode(old.getCode());
        }
        // 将编辑的name和code 复制到 alias中
        form.setNameAlias(json.getString("name"));
        form.setCodeAlias(json.getString("code"));
        
//        if(form.getFormType() == 6 || form.getFormType() == 7) {
            form.setReName(json.getString("re_name"));
//        }

        if(form.getCheckStatus() >= 0) {
            voRes = this.vaiidate(form, json);
            if(!voRes.getSuccess()) {
                return voRes;
            }
        }
        // 修改图片
        if (WzStrUtil.isNotBlank(json.getString("picLogo"))) {
            try {
                json.put("picLogo", getImageName(json,"picLogo"));
            } catch (Exception ex) {
                json.put("picLogo", json.getString("picLogo"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picOrgLicense"))) {
            try {
                json.put("picOrgLicense", getImageName(json,"picOrgLicense"));
            } catch (Exception ex) {
                json.put("picOrgLicense", json.getString("picOrgLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpLicense"))) {
            try {
                json.put("picLpLicense", getImageName(json,"picLpLicense"));
            } catch (Exception ex) {
                json.put("picLpLicense", json.getString("picLpLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardFront"))) {
            try {
                json.put("picLpIdCardFront", getImageName(json,"picLpIdCardFront"));
            } catch (Exception ex) {
                json.put("picLpIdCardFront", json.getString("picLpIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardBack"))) {
            try {
                json.put("picLpIdCardBack", getImageName(json,"picLpIdCardBack"));
            } catch (Exception ex) {
                json.put("picLpIdCardBack", json.getString("picLpIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardInHand"))) {
            try {
                json.put("picLpIdCardInHand", getImageName(json,"picLpIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLpIdCardInHand", json.getString("picLpIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardFront"))) {
            try {
                json.put("picLmIdCardFront", getImageName(json,"picLmIdCardFront"));
            } catch (Exception ex) {
                json.put("picLmIdCardFront", json.getString("picLmIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardBack"))) {
            try {
                json.put("picLmIdCardBack", getImageName(json,"picLmIdCardBack"));
            } catch (Exception ex) {
                json.put("picLmIdCardBack", json.getString("picLmIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardInHand"))) {
            try {
                json.put("picLmIdCardInHand", getImageName(json,"picLmIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLmIdCardInHand", json.getString("picLmIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picCommitmentLetter"))) {
            try {
                json.put("picCommitmentLetter", getImageName(json,"picCommitmentLetter"));
            } catch (Exception ex) {
                json.put("picCommitmentLetter", json.getString("picCommitmentLetter"));
            }
        }
        form.setDetail(JSONObject.toJSONString(json));
        result = this.saveOrUpdate(form);
        
        if(result <= 0) {
            voRes.setFail(voRes);
            voRes.setMessage("保存资源信息失败");
            return voRes;
        }
        
        if(form.getCheckStatus() == 1) {
//            form.setChecker(user.getUserName());
//            voRes = this.saveFormHisToLib(form, json);
            checkUserDetail(form.getId());
        }
        return voRes;
    }

    @Override
    @Transactional
    public VoResponse addLibBatch(JSONArray updDatas, int userType) {

        StringBuilder errMsgBuilder = new StringBuilder("");
        VoResponse doVoRes = null;
        VoResponse rsltVoRes = new VoResponse();
        User user = this.getUser();
        if (null == user) {
            rsltVoRes.setFail(rsltVoRes);
            rsltVoRes.setMessage("未登录或已超时，请重新登录");
            return rsltVoRes;
        }
        BusUserForm form = null;
        for(int i = 0;i < updDatas.size();i++) {
            form = new BusUserForm();
            form.setFormType(userType);
            // 批量导入
//            if(user.getUserType() != 0) {
                form.setCheckStatus(0);
//            }
            form.setDetail(updDatas.getJSONObject(i).toJSONString());
            try {
                doVoRes = addLib(form);
            } catch (Exception ex) {
                doVoRes = new VoResponse();
                doVoRes.setFail(doVoRes);
                doVoRes.setMessage("导入数据发生业务异常[" + ex.getMessage() + "]");
            }

            if(!doVoRes.getSuccess()) {
                errMsgBuilder.append("第" + i + "条数据保存错误：" + doVoRes.getMessage()).append(";");
            }
        }
        if (WzStrUtil.isNotBlank(errMsgBuilder.toString())) {
            rsltVoRes.setFail(rsltVoRes);
            rsltVoRes.setMessage(errMsgBuilder.toString());
        } else {
            rsltVoRes.setSuccess(rsltVoRes);
            rsltVoRes.setMessage("数据导入已完成");
        }
        return rsltVoRes;
    }

    @Override
    public VoResponse delLib(String id, String type) {
        VoResponse voRes = new VoResponse();
        if(type.equals("1")) {
            LibExpert lib = libExpertMapper.findById(id);
            if(lib != null) {
                libExpertMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
                if(lib != null && lib.getUserId() != null) {
                    busUserMapper.updateCheckStatus(1,lib.getUserId());
                }
            }
        }else if(type.equals("2")) {
            LibEnterprise lib = libEnterpriseMapper.findById(id);
            if(lib != null) {
                libEnterpriseMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
                if(lib != null && lib.getUserId() != null) {
                    busUserMapper.updateCheckStatus(1,lib.getUserId());
                }
            }
        }else if(type.equals("3")) {
            LibServices lib = libServiceMapper.findById(id);
            if(lib != null) {
                libServiceMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
                if(lib != null && lib.getUserId() != null) {
                    busUserMapper.updateCheckStatus(1,lib.getUserId());
                }
            }
        }else if(type.equals("4")) {
            LibCollege lib = libCollegeMapper.findById(id);
            if(lib != null) {
                libCollegeMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
                if(lib != null && lib.getUserId() != null) {
                    busUserMapper.updateCheckStatus(1,lib.getUserId());
                }
            }
        }else if(type.equals("6")) {
            LibResults lib = libResMapper.findById(id);
            if(lib != null) {
                libResMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
//                if(lib != null && lib.getUserId() != null) {
//                    busUserMapper.updateCheckStatus(1,lib.getUserId());
//                }
            }
        }else if(type.equals("7")) {
            LibRequirements lib = libReqMapper.findById(id);
            if(lib != null) {
                libReqMapper.del(id);
                busUserFormHisMapper.del(lib.getFormId());
                busUserCheckMapper.delByFormId(lib.getFormId());
//                if(lib != null && lib.getUserId() != null) {
//                    busUserMapper.updateCheckStatus(1,lib.getUserId());
//                }
            }
        }
        return voRes;
    }
    
    @Override
    public VoResponse delForm(String id) {
        VoResponse voRes = new VoResponse();
        busUserFormHisMapper.del(id);
        return voRes;
    }
    
    public int saveOrUpdate(BusUserForm e) {
        int result;
        if(e.getId() == null) {
            result = busUserFormHisMapper.insert(e);
        }else {
            result = busUserFormHisMapper.update(e);
        }
        return result;
    }

    @Override
    public int saveFormHis(String form) {
        User user = this.getUser();
        BusUserForm e = busUserFormHisMapper.findByUserIdAndCheck(user.getUserType(), user.getUserId(), -1);
        int result = 0;
        JSONObject json = null;
        try {
            json = JSON.parseObject(form);
        }catch (Exception ex) {
            logger.error("解析资源库数据异常", e);
            return 0;
        }
        // 修改图片
        if (WzStrUtil.isNotBlank(json.getString("picLogo"))) {
            try {
                json.put("picLogo", getImageName(json,"picLogo"));
            } catch (Exception ex) {
                json.put("picLogo", json.getString("picLogo"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picOrgLicense"))) {
            try {
                json.put("picOrgLicense", getImageName(json,"picOrgLicense"));
            } catch (Exception ex) {
                json.put("picOrgLicense", json.getString("picOrgLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpLicense"))) {
            try {
                json.put("picLpLicense", getImageName(json,"picLpLicense"));
            } catch (Exception ex) {
                json.put("picLpLicense", json.getString("picLpLicense"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardFront"))) {
            try {
                json.put("picLpIdCardFront", getImageName(json,"picLpIdCardFront"));
            } catch (Exception ex) {
                json.put("picLpIdCardFront", json.getString("picLpIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardBack"))) {
            try {
                json.put("picLpIdCardBack", getImageName(json,"picLpIdCardBack"));
            } catch (Exception ex) {
                json.put("picLpIdCardBack", json.getString("picLpIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLpIdCardInHand"))) {
            try {
                json.put("picLpIdCardInHand", getImageName(json,"picLpIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLpIdCardInHand", json.getString("picLpIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardFront"))) {
            try {
                json.put("picLmIdCardFront", getImageName(json,"picLmIdCardFront"));
            } catch (Exception ex) {
                json.put("picLmIdCardFront", json.getString("picLmIdCardFront"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardBack"))) {
            try {
                json.put("picLmIdCardBack", getImageName(json,"picLmIdCardBack"));
            } catch (Exception ex) {
                json.put("picLmIdCardBack", json.getString("picLmIdCardBack"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picLmIdCardInHand"))) {
            try {
                json.put("picLmIdCardInHand", getImageName(json,"picLmIdCardInHand"));
            } catch (Exception ex) {
                json.put("picLmIdCardInHand", json.getString("picLmIdCardInHand"));
            }
        }
        if (WzStrUtil.isNotBlank(json.getString("picCommitmentLetter"))) {
            try {
                json.put("picCommitmentLetter", getImageName(json,"picCommitmentLetter"));
            } catch (Exception ex) {
                json.put("picCommitmentLetter", json.getString("picCommitmentLetter"));
            }
        }
        if(e == null) {
            e = new BusUserForm();
//            e.setDetail(form);
            e.setDetail(JSONObject.toJSONString(json));
            e.setFormType(user.getUserType());
            e.setCheckStatus(-1);
            e.setUserId(user.getUserId());
            e.setName(user.getName());
            e.setCode(user.getCode());
            e.setCreater(user.getUserName());
            result = busUserFormHisMapper.insert(e);
        }else {
//            e.setDetail(form);
            e.setDetail(JSONObject.toJSONString(json));
            e.setUpdater(user.getUserName());
            result = busUserFormHisMapper.update(e);
        }
        return result;
    }
    
    boolean saveOrUpdate(LibExpert e) {
        int result;
        if(e.getId() == null) {
            result = libExpertMapper.insert(e);
        }else {
            result = libExpertMapper.update(e);
        }
        if(result > 0) {
            return true;
        }
        return false;
    }
    
    boolean saveOrUpdate(LibEnterprise e) {
        int result;
        if(e.getId() == null) {
            result = libEnterpriseMapper.insert(e);
        }else {
            result = libEnterpriseMapper.update(e);
        }
        if(result > 0) {
            return true;
        }
        return false;
    }
    
    boolean saveOrUpdate(LibServices e) {
        int result;
        if(e.getId() == null) {
            result = libServiceMapper.insert(e);
        }else {
            result = libServiceMapper.update(e);
        }
        if(result > 0) {
            return true;
        }
        return false;
    }
    
    boolean saveOrUpdate(LibCollege e) {
        int result;
        if(e.getId() == null) {
            result = libCollegeMapper.insert(e);
        }else {
            result = libCollegeMapper.update(e);
        }
        if(result > 0) {
            return true;
        }
        return false;
    }

    @Override
    public VoResponse vaiidate(BusUserForm e, JSONObject json) {
        // 验证逻辑
        VoResponse voRes = new VoResponse();
        if(UserTypeEnum.Expert.key() == e.getFormType()) {
            if(StringUtils.isEmpty(e.getName()) || StringUtils.isEmpty(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("专家姓名和身份证号不能为空");
                return voRes;
            }
            // 性别
            if (WzStrUtil.isBlank(json.getString("sex"))
                    || (!"1".equals(json.getString("sex")) && !"0".equals(json.getString("sex")))) {
                voRes.setFail(voRes);
                voRes.setMessage("性别不能为空或信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 所在区域
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 学历
            if (WzStrUtil.isBlank(json.getString("edu"))) {
                voRes.setFail(voRes);
                voRes.setMessage("学历不能为空，请按照正确的样例填写");
                return voRes;
            }
            String xldef = "5,6,7,99";
            if (0 > xldef.indexOf(json.getString("edu"))) {
                voRes.setFail(voRes);
                voRes.setMessage("学历录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 学位
            if (WzStrUtil.isBlank(json.getString("academic"))) {
                voRes.setFail(voRes);
                voRes.setMessage("学位不能为空，请按照正确的样例填写");
                return voRes;
            }
            String xwdef = "1,2,3,99";
            if (0 > xwdef.indexOf(json.getString("academic"))) {
                voRes.setFail(voRes);
                voRes.setMessage("学位录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 研究领域
            if (WzStrUtil.isBlank(json.getString("research_field"))) {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray darr = null;
            try {
                darr = JSON.parseArray(json.getString("research_field"));
            } catch (Exception ex) {
                darr = null;
            }
            String lydef = "1,2,3,4,5,6,7,99";
            if (null != darr && 0 < darr.size()) {
                for (int i = 0; i < darr.size(); i++) {
                    if (0 > lydef.indexOf((String) darr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("领域录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            // 手机号码
            if (!WzStrUtil.isMobile(json.getString("mobilephone"))
                    && !WzStrUtil.isPhone(json.getString("mobilephone"))) {
                voRes.setFail(voRes);
                voRes.setMessage("格式错误，请输入正确的手机号码");
                return voRes;
            }
            // 邮箱
            if (!WzStrUtil.isEmail(json.getString("fdemail"))) {
                voRes.setFail(voRes);
                voRes.setMessage("格式错误，请输入正确的电子邮箱");
                return voRes;
            }
        }else if(UserTypeEnum.Enterprise.key() == e.getFormType()) {
            if(WzStrUtil.isBlank(e.getName()) || WzStrUtil.isBlank(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("企业名称和统一社会信用代码不能为空");
                return voRes;
            }
            // 企业规模
//            if (WzStrUtil.isBlank(json.getString("registered_capital"))) {
//                voRes.setFail(voRes);
//                voRes.setMessage("企业规模不能为空，请按照正确的样例填写");
//                return voRes;
//            }
//            JSONArray gmarr = null;
//            try {
//                gmarr = JSON.parseArray(json.getString("registered_capital"));
//            } catch (Exception ex) {
//                gmarr = null;
//            }
//            String gmdef = "1,2,3,4,5,6";
//            if (null != gmarr && 0 < gmarr.size()) {
//                for (int i = 0; i < gmarr.size(); i++) {
//                    if (0 > gmdef.indexOf((String) gmarr.get(i))) {
//                        voRes.setFail(voRes);
//                        voRes.setMessage("企业规模录入信息错误，请按照正确的样例填写");
//                        return voRes;
//                    }
//                }
//            } else {
//                voRes.setFail(voRes);
//                voRes.setMessage("企业规模不能为空，请按照正确的样例填写");
//                return voRes;
//            }
            // 注册类型
//            if (WzStrUtil.isBlank(json.getString("registered_type"))) {
////                voRes.setFail(voRes);
////                voRes.setMessage("注册类型不能为空，请按照正确的样例填写");
////                return voRes;
////            }
////            JSONArray tyarr = null;
////            try {
////                tyarr = JSON.parseArray(json.getString("registered_type"));
////            } catch (Exception ex) {
////                tyarr = null;
////            }
////            String tydef = "1,2,3";
////            if (null != tyarr && 0 < tyarr.size()) {
////                for (int i = 0; i < tyarr.size(); i++) {
////                    if (0 > tydef.indexOf((String) tyarr.get(i))) {
////                        voRes.setFail(voRes);
////                        voRes.setMessage("注册类型录入信息错误，请按照正确的样例填写");
////                        return voRes;
////                    }
////                }
////            } else {
////                voRes.setFail(voRes);
////                voRes.setMessage("注册类型不能为空，请按照正确的样例填写");
////                return voRes;
////            }
            // 所在区域
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 是否上市
            if (WzStrUtil.isBlank(json.getString("registerMarket"))) {
                voRes.setFail(voRes);
                voRes.setMessage("是否上市不能为空，请按照正确的样例填写");
                return voRes;
            }
            String ssdef = "0,1";
            if (0 > ssdef.indexOf(json.getString("registerMarket"))) {
                voRes.setFail(voRes);
                voRes.setMessage("是否上市录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 所属领域
            if (WzStrUtil.isBlank(json.getString("domain"))) {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray darr = null;
            try {
                darr = JSON.parseArray(json.getString("domain"));
            } catch (Exception ex) {
                darr = null;
            }
            String lydef = "1,2,3,4,5,6,99";
            if (null != darr && 0 < darr.size()) {
                for (int i = 0; i < darr.size(); i++) {
                    if (0 > lydef.indexOf((String) darr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("领域录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            // 联系人姓名
            if (WzStrUtil.isBlank(json.getString("lxname"))) {
                voRes.setFail(voRes);
                voRes.setMessage("联系人姓名不能为空，请按照正确的样例填写");
                return voRes;
            }
            boolean isPhoneOk = true;
            boolean isEmailOk = true;
            // 联系人手机
            if (WzStrUtil.isBlank(json.getString("lxphone"))) {
                isPhoneOk = false;
            } else {
                if (!WzStrUtil.isMobile(json.getString("lxphone"))
                        && !WzStrUtil.isPhone(json.getString("lxphone"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("格式错误，请输入正确的手机或电话号码");
                    return voRes;
                }
            }
            // 联系人邮箱
            if (WzStrUtil.isBlank(json.getString("lxemail"))) {
                isEmailOk = false;
            } else {
                if (!WzStrUtil.isEmail(json.getString("lxemail"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("格式错误，请输入正确的电子邮箱");
                    return voRes;
                }
            }
            if (!isEmailOk && !isPhoneOk) {
                voRes.setFail(voRes);
                voRes.setMessage("手机或电子邮箱必填一项");
                return voRes;
            }

        }else if(UserTypeEnum.Service.key() == e.getFormType()) {
            if(StringUtils.isEmpty(e.getName()) || StringUtils.isEmpty(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("服务机构名称和统一社会信用代码不能为空");
                return voRes;
            }
            // 所在地区
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            // 机构性质
            if (WzStrUtil.isBlank(json.getString("registerNature"))) {
                voRes.setFail(voRes);
                voRes.setMessage("机构性质不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray xzarr = null;
            try {
                xzarr = JSON.parseArray(json.getString("registerNature"));
            } catch (Exception ex) {
                xzarr = null;
            }
            String xzdef = "1,2,3,99";
            if (null != xzarr && 0 < xzarr.size()) {
                for (int i = 0; i < xzarr.size(); i++) {
                    if (0 > xzdef.indexOf((String) xzarr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("机构性质录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("机构性质不能为空，请按照正确的样例填写");
                return voRes;
            }
            // 机构类别
            if (WzStrUtil.isBlank(json.getString("orgType"))) {
                voRes.setFail(voRes);
                voRes.setMessage("机构类别不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray tyarr = null;
            try {
                tyarr = JSON.parseArray(json.getString("orgType"));
            } catch (Exception ex) {
                tyarr = null;
            }
            String tydef = "1,2,3,4,5,6,7,8,9,10,99";
            if (null != tyarr && 0 < tyarr.size()) {
                for (int i = 0; i < tyarr.size(); i++) {
                    if (0 > tydef.indexOf((String) tyarr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("机构类别录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("机构类别不能为空，请按照正确的样例填写");
                return voRes;
            }
            // 机构联系人
            if (WzStrUtil.isBlank(json.getString("linkman"))) {
                voRes.setFail(voRes);
                voRes.setMessage("联系人姓名不能为空，请按照正确的样例填写");
                return voRes;
            }
            boolean isPhoneOk = true;
            boolean isEmailOk = true;
            // 联系人手机
            if (WzStrUtil.isBlank(json.getString("lxphone"))
                    && WzStrUtil.isBlank(json.getString("lxtel"))) {
                isPhoneOk = false;
            } else {
                if (!WzStrUtil.isMobile(json.getString("lxphone"))
                        && !WzStrUtil.isPhone(json.getString("lxtel"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("格式错误，请输入正确的手机或电话号码");
                    return voRes;
                }
            }
            // 联系人邮箱
            if (WzStrUtil.isBlank(json.getString("lxemail"))) {
                isEmailOk = false;
            } else {
                if (!WzStrUtil.isEmail(json.getString("lxemail"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("格式错误，请输入正确的电子邮箱");
                    return voRes;
                }
            }
            if (!isEmailOk && !isPhoneOk) {
                voRes.setFail(voRes);
                voRes.setMessage("手机或电子邮箱必填一项");
                return voRes;
            }
        }else if(UserTypeEnum.College.key() == e.getFormType()) {
            if(StringUtils.isEmpty(e.getName()) || StringUtils.isEmpty(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("高校院所名称和统一社会信用代码不能为空");
                return voRes;
            }
            // 所在区域
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            if (WzStrUtil.isNotBlank(json.getString("lxmobile"))) {
                if (!WzStrUtil.isMobile(json.getString("lxmobile"))
                        && !WzStrUtil.isPhone(json.getString("lxmobile"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("手机号码格式错误，请按照正确的样例填写");
                    return voRes;
                }
            }
            if (WzStrUtil.isNotBlank(json.getString("lxemail"))) {
                if (!WzStrUtil.isEmail(json.getString("lxemail"))) {
                    voRes.setFail(voRes);
                    voRes.setMessage("邮箱格式错误，请按照正确的样例填写");
                    return voRes;
                }
            }
        }else if(UserTypeEnum.Results.key() == e.getFormType()) {
            if(WzStrUtil.isBlank(e.getReName())
                    || WzStrUtil.isBlank(e.getName())
                    || WzStrUtil.isBlank(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("成果名称、成果单位名称及统一社会信用信息不能为空");
                return voRes;
            }
            // 所在地区
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            boolean isFzOk = false;
            boolean isLxOk = false;
            if (WzStrUtil.isNotBlank(json.getString("fzname"))
                    && ((WzStrUtil.isMobile(json.getString("fzphone")) || WzStrUtil.isPhone(json.getString("fzphone")))
                        || WzStrUtil.isEmail(json.getString("fzemail")))) {
                isFzOk = true;
            }
            if (WzStrUtil.isNotBlank(json.getString("fzname2"))
                    && ((WzStrUtil.isMobile(json.getString("fzphone2")) || WzStrUtil.isPhone(json.getString("fzphone2")))
                        || WzStrUtil.isEmail(json.getString("fzemail2")))) {
                isLxOk = true;
            }
            if (!isFzOk && !isLxOk) {
                voRes.setFail(voRes);
                voRes.setMessage("负责人信息和联系人信息至少正确填写一套，请注意手机号码和邮箱的格式");
                return voRes;
            }
            // 所属领域
            if (WzStrUtil.isBlank(json.getString("domain"))) {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray darr = null;
            try {
                darr = JSON.parseArray(json.getString("domain"));
            } catch (Exception ex) {
                darr = null;
            }
            String lydef = "1,2,3,4,5,6,99";
            if (null != darr && 0 < darr.size()) {
                for (int i = 0; i < darr.size(); i++) {
                    if (0 > lydef.indexOf((String) darr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("领域录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
        }else if(UserTypeEnum.Requirement.key() == e.getFormType()) {
            if(WzStrUtil.isBlank(e.getReName())
                    || WzStrUtil.isBlank(e.getName())
                    || WzStrUtil.isBlank(e.getCode())) {
                voRes.setFail(voRes);
                voRes.setMessage("需求名称、需求单位名称及统一社会信用信息不能为空");
                return voRes;
            }
            // 所在地区
            if (WzStrUtil.isBlank(json.getString("country"))) {
                voRes.setFail(voRes);
                voRes.setMessage("地域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray carr = null;
            try {
                carr = JSON.parseArray(json.getString("country"));
            } catch (Exception ex) {
                carr = null;
            }
            if (null == carr || 0 == carr.size() || 3 < carr.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("地域录入信息错误，请按照正确的样例填写");
                return voRes;
            }
            boolean isFzOk = false;
            boolean isLxOk = false;
            if (WzStrUtil.isNotBlank(json.getString("fzname"))
                    && ((WzStrUtil.isMobile(json.getString("fzphone")) || WzStrUtil.isPhone(json.getString("fzphone")))
                        || WzStrUtil.isEmail(json.getString("fzemail")))) {
                isFzOk = true;
            }
            if (WzStrUtil.isNotBlank(json.getString("fzname2"))
                    && ((WzStrUtil.isMobile(json.getString("fzphone2")) || WzStrUtil.isPhone(json.getString("fzphone2")))
                        || WzStrUtil.isEmail(json.getString("fzemail2")))) {
                isLxOk = true;
            }
            if (!isFzOk && !isLxOk) {
                voRes.setFail(voRes);
                voRes.setMessage("负责人信息和联系人信息至少正确填写一套，请注意手机号码和邮箱的格式");
                return voRes;
            }

            // 所属领域
            if (WzStrUtil.isBlank(json.getString("domain"))) {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
            JSONArray darr = null;
            try {
                darr = JSON.parseArray(json.getString("domain"));
            } catch (Exception ex) {
                darr = null;
            }
            String lydef = "1,2,3,4,5,6,99";
            if (null != darr && 0 < darr.size()) {
                for (int i = 0; i < darr.size(); i++) {
                    if (0 > lydef.indexOf((String) darr.get(i))) {
                        voRes.setFail(voRes);
                        voRes.setMessage("领域录入信息错误，请按照正确的样例填写");
                        return voRes;
                    }
                }
            } else {
                voRes.setFail(voRes);
                voRes.setMessage("领域不能为空，请按照正确的样例填写");
                return voRes;
            }
        }
        return voRes;
    }
    
    private VoResponse saveFormHisToExpert(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibExpert e = null;
        e = libExpertMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibExpert();
            //e.setCheckStatus(1);
            e.setCreditLevel("5");//默认5
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
            e.setName(json.getString("name"));//专家姓名
            e.setCode(json.getString("code"));//专家身份证号
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
            if(libExpertMapper.findByNameAndCode(e.getName(), e.getCode()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("专家已经存在");
                return voRes;
            }
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        e.setName(json.getString("name"));//专家姓名
        e.setCode(json.getString("code"));//专家身份证号
        e.setUpdater(form.getUpdater());
        e.setSex(json.getString("sex"));
        e.setBirthday(json.getString("bornDate"));
        e.setEducation(json.getString("edu"));
        e.setDegree(json.getString("academic"));
        e.setSchool(json.getString("shcool"));
        e.setCellphone(json.getString("mobilephone"));//手机号
        e.setTelephone(json.getString("telphone"));
        e.setEmail(json.getString("fdemail"));
        e.setResearchField(json.getString("research_field"));//研究领域
        e.setResearchFieldOther(json.getString("researchFieldOther"));//研究领域
        e.setResearchArea(json.getString("research_area"));//研究方向
        e.setCountry(json.getString("country"));//所在地区
        e.setAddress(json.getString("address"));//通讯地址
        e.setWorkUnit(json.getString("work_unit"));//工作单位
        e.setWorkDepartment(json.getString("work_bumen"));
        e.setJobTitle(json.getString("zwname"));
        e.setTitle(json.getString("zcname"));
        e.setTitleLevel(json.getString("zclevel"));
        e.setProjectDesc(json.getString("project_desc"));//主要产学研合作项目情况
        e.setSuccessRecord(json.getString("success_record"));//主要学术成就/研究成果/管理成就
        e.setResearchWinning(json.getString("research_record"));
        e.setSearchParam(json.getString("search_param"));
        //e.setProject(json.getString("zcname"));
        this.saveOrUpdate(e);
        LibImage imgs = new LibImage();
        imgs.setCreater(form.getCreater());

//        imgs.setField1(json.getString("picLogo"));
//        imgs.setField7(json.getString("picLmIdCardFront"));
//        imgs.setField8(json.getString("picLmIdCardBack"));
//        imgs.setField9(json.getString("picLmIdCardInHand"));
        try {
            imgs.setField1(this.getImageName(json, "picLogo")); // 日常
            imgs.setField7(this.getImageName(json, "picLmIdCardFront")); // 正面
            imgs.setField8(this.getImageName(json, "picLmIdCardBack")); // 反面
            imgs.setField9(this.getImageName(json, "picLmIdCardInHand")); // 手持

        }catch (Exception ex) {
//            ex.printStackTrace();
            imgs.setField1(json.getString("picLogo"));
            imgs.setField7(json.getString("picLmIdCardFront"));
            imgs.setField8(json.getString("picLmIdCardBack"));
            imgs.setField9(json.getString("picLmIdCardInHand"));
        }
        imgs.setLibId(e.getId());
        libImageService.saveOrUpdate(imgs);
        return voRes;
    }
    
    private String getImageName(JSONObject json, String s){
        String name = null;
        String jaStr = json.getString(s);
        JSONArray ja = null;
        if (WzStrUtil.isNotBlank(jaStr)) {
            if (jaStr.startsWith("[") && jaStr.endsWith("]")) {
                ja = json.getJSONArray(s);
            } else {
                return json.getString(s);
            }
        } else {
            return "";
        }
        if (null == ja || 0 == ja.size()) {
            return "";
        } else {
            name = json.getJSONArray(s).getJSONObject(0).getString("url");
            if (name.startsWith(tomcatAddr)) {
                name = name.substring(tomcatAddr.length());
            } else if (name.startsWith(tomcatPath)) {
                name = name.substring(tomcatPath.length());
            }
//            name = name.substring(name.lastIndexOf("/") + 1, name.length());
        }
        return name;
    }
    
    public static void main(String[] args) {
        String name = "http://106.14.172.38:8990/jmrhupload/user/153542017807779994.png";
        System.out.println(name.substring(name.lastIndexOf("/"), name.length()));
        
        String jsonnull = "{\"onepicture\":[]}";
        String jsonss = "[{\"name\":\"1.png\",\"url\":\"http::\"},{\"name\":\"2.png\",\"url\":\"http:\"}]";
        JSONArray json = null;
        json = JSON.parseArray(jsonss);
        System.out.println(json.isEmpty());
        System.out.println(json.getJSONObject(0).get("name"));
        System.out.println(JSON.parseObject(json.get(0).toString()).get("name"));
        
        json = JSON.parseObject(jsonnull).getJSONArray("onepicture");
        System.out.println(json);
        System.out.println(json.isEmpty());
    }
    
    private VoResponse saveFormHisToEnterprise(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibEnterprise e = null;
        e = libEnterpriseMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibEnterprise();
            //e.setCheckStatus(1);
            e.setCreditLevel("5");
            e.setCode(json.getString("code"));
            if(libEnterpriseMapper.findByNameAndCode(json.getString("name"), e.getCode()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("企业已经存在");
                return voRes;
            }
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
            //e.setCreater(form.getCreater());
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        e.setUpdater(form.getUpdater());
        e.setName(json.getString("name"));
        e.setRegisteredCapital(json.getString("registered_capital"));
        e.setRegisteredType(json.getString("registered_type"));
        e.setRegisteredTime(json.getString("registerDate"));
        e.setIsHighNewTech(json.getString("is_high_new_tech"));

        e.setCountry(json.getString("country"));
        e.setAddress(json.getString("registeraddress"));
        e.setZipCode(json.getString("registerecode"));
        e.setLocationNature(json.getString("registerSite"));
        e.setLocationNatureOther(json.getString("registerSiteOther"));
        e.setHighTechZone(json.getString("registerHSite"));
        e.setHighTechZoneOther(json.getString("registerHSiteOther"));
        e.setIsListed(json.getString("registerMarket"));
        e.setStockCode(json.getString("stockCode"));
        e.setListedPlace(json.getString("registerMarkeSite"));
        e.setListedPlaceOther(json.getString("registerMarkeSiteOther"));
        e.setDomain(json.getString("domain"));
        e.setDomainOther(json.getString("domainOther"));
        e.setProduct(json.getString("product"));
        e.setInventionNum(json.getString("inventionNum"));
        e.setNewDrugNum(json.getString("newDrugnum"));
        e.setUtilityModelNum(json.getString("utilityModel"));
        e.setIcNum(json.getString("integratedCircuitnum"));
        e.setDesignNum(json.getString("designnum"));
        e.setNationalNum(json.getString("nationalNum"));
        e.setSoftwareNum(json.getString("softwareNum"));
        e.setOtherInventionNum(json.getString("othernum"));

        e.setDeveloperNumber(json.getString("researchTeamnum"));
        e.setUndergraduateNum(json.getString("bachelorAbovenum"));
        e.setSeniorNum(json.getString("middleLevelnum"));
        e.setHighTitleNum(json.getString("highleveltalentsnum"));
        e.setHighTitleType(json.getString("highleveltalentType"));
        e.setHighTitleTypeOther(json.getString("comhighleveltalentTypeOther"));

        e.setRdAmountLast(json.getString("service_research_last"));
        e.setRdAmountBefore(json.getString("service_research_before"));
        e.setRdAmountPrevious(json.getString("service_research_previous"));

        e.setPlatform(json.getString("platform"));
        e.setPlatformOther(json.getString("platformOther"));

        e.setIsResearchWeapon(json.getString("sfkyrw"));
        e.setWeaponThreeEvidence(json.getString("szget"));
        e.setSecrecyOneTime(json.getString("qdtime1"));
        e.setSecrecyTwoTime(json.getString("qdtime2"));
        e.setSecrecyThreeTime(json.getString("qdtime3"));
        e.setProduceTime(json.getString("qdtime4"));
        e.setSupplierTime(json.getString("qdtime5"));
        e.setPlanApply(json.getString("szwhd"));

        e.setManagement(json.getString("jmrhgn"));
        e.setManagementName(json.getString("jmrhgnName"));
        e.setManagementZw(json.getString("jmrhgnZW"));
        e.setManagementPhone(json.getString("jmrhgnTel"));

        e.setJmrhDifficulty(json.getString("ydkn"));
        e.setJmrhDifficultyOther(json.getString("comydknOther"));
        e.setJmrhProblem(json.getString("problem"));
        e.setJmrhTech(json.getString("jscg"));
        e.setSharedResources(json.getString("zyqk"));
        e.setJmrhSuggest(json.getString("xgjy"));

        e.setProject(json.getString("comPorcolumnDefinitions"));
        e.setSearchParam(json.getString("search_param"));

        e.setLxname(json.getString("lxname"));
        e.setLxzw(json.getString("lxzw"));
        e.setLxphone(json.getString("lxphone"));
        e.setLxemail(json.getString("lxemail"));
        e.setLpname(json.getString("lpname"));
        e.setLpzw(json.getString("lpzw"));
        e.setLpphone(json.getString("lpphone"));
        e.setLpemail(json.getString("lpemail"));
        this.saveOrUpdate(e);
        this.saveLibOrgImage(json, e.getId());
        return voRes;
    }
    
    private VoResponse saveFormHisToServices(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibServices e = null;
        e = libServiceMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibServices();
            //e.setCheckStatus(1);
            e.setCreditLevel("5");
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
            e.setCode(json.getString("code"));
            //e.setCreater(form.getCreater());
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
            if(libServiceMapper.findByNameAndCode(json.getString("name"), e.getCode()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("服务机构已经存在");
                return voRes;
            }
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        e.setUpdater(form.getUpdater());
        e.setName(json.getString("name"));
        e.setCountry(json.getString("country"));
        e.setAddress(json.getString("address"));
        e.setZipCode(json.getString("ecode"));

        e.setOrgNature(json.getString("registerNature"));
        e.setOrgNatureOther(json.getString("mechregisterNatureOther"));
        e.setOrgType(json.getString("orgType"));
        e.setOrgTypeOther(json.getString("orgTypeOther"));

        e.setServicesProvided(json.getString("serviceAbout"));

        e.setServiceAmountLast(json.getString("service_amount_last"));
        e.setServiceAmountBefore(json.getString("service_amount_before"));
        e.setServiceAmountPrevious(json.getString("service_amount_previous"));
        e.setServiceQuantityLast(json.getString("service_quantity_last"));
        e.setServiceQuantityBefore(json.getString("service_quantity_before"));
        e.setServiceQuantityPrevious(json.getString("service_quantity_previous"));

        e.setLpname(json.getString("fdname"));
        e.setLpphone(json.getString("fdtel"));
        e.setLpmobile(json.getString("fdphone"));
        e.setLpemail(json.getString("fdemail"));
        e.setLinkman(json.getString("linkman"));
        e.setLxzw(json.getString("lxzw"));
        e.setLxphone(json.getString("lxtel"));
        e.setLxmobile(json.getString("lxphone"));
        e.setLxemail(json.getString("lxemail"));

        e.setPersonnelNumber(json.getString("perNum"));
        e.setUndergraduateNumber(json.getString("underPer"));
        e.setMiddleTitleNumber(json.getString("MHPer"));

        e.setProject(json.getString("PorcolumnDefinitions"));
        e.setHonor(json.getString("honor"));
        e.setWorkResult(json.getString("workrPorcolumnDefinitions"));

        e.setSearchParam(json.getString("search_param"));
        this.saveOrUpdate(e);
        this.saveLibOrgImage(json, e.getId());
        return voRes;
    }
    
    private VoResponse saveFormHisToCollege(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibCollege e = null;
        e = libCollegeMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibCollege();
            //e.setCheckStatus(1);
            e.setCreditLevel("5");
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
            e.setCode(json.getString("code"));
            //e.setCreater(form.getCreater());
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
            if(libExpertMapper.findByNameAndCode(e.getName(), e.getCode()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("高校院所已经存在");
                return voRes;
            }
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        e.setUpdater(form.getUpdater());
        e.setName(json.getString("name"));
        e.setCountry(json.getString("country"));
        e.setAddress(json.getString("adress"));
        e.setZipCode(json.getString("zip_code"));
        e.setUnitUrl(json.getString("unit_url"));
        e.setMajorPlatform(json.getString("major_platform"));
        e.setIntroduction(json.getString("introduction"));
        e.setLxName(json.getString("lxname"));
        e.setLxMobile(json.getString("lxmobile"));
        e.setLxEmail(json.getString("lxemail"));
        e.setSearchParam(json.getString("search_param"));
        this.saveOrUpdate(e);
        this.saveLibOrgImage(json, e.getId());
        return voRes;
    }
    
    boolean saveLibOrgImage(JSONObject json, String libId){
        LibImage imgs = new LibImage();
        imgs.setCreater(getUserName());

//        imgs.setField1(json.getString("picLogo"));//logo
//        imgs.setField2(json.getString("picOrgLicense"));//营业执照
//        imgs.setField3(json.getString("picLpLicense"));//事业单位法人证书副本
//        imgs.setField7(json.getString("picLmIdCardFront"));//联系人身份证正面
//        imgs.setField8(json.getString("picLmIdCardBack"));//联系人身份证背面
//        imgs.setField9(json.getString("picLmIdCardInHand"));//联系人身份证手持
        try {
            imgs.setField1(this.getImageName(json, "picLogo"));
            imgs.setField2(this.getImageName(json, "picOrgLicense"));
            imgs.setField3(this.getImageName(json, "picLpLicense"));
            imgs.setField7(this.getImageName(json, "picLmIdCardFront"));
            imgs.setField8(this.getImageName(json, "picLmIdCardBack"));
            imgs.setField9(this.getImageName(json, "picLmIdCardInHand"));
        }catch (Exception ex) {
            ex.printStackTrace();
            imgs.setField1(json.getString("picLogo"));//logo
            imgs.setField2(json.getString("picOrgLicense"));//营业执照
            imgs.setField3(json.getString("picLpLicense"));//事业单位法人证书副本
            imgs.setField7(json.getString("picLmIdCardFront"));//联系人身份证正面
            imgs.setField8(json.getString("picLmIdCardBack"));//联系人身份证背面
            imgs.setField9(json.getString("picLmIdCardInHand"));//联系人身份证手持
        }
        imgs.setLibId(libId);
        libImageService.saveOrUpdate(imgs);
        return true;
    }
    
    private VoResponse saveFormHisToReq(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibRequirements e = null;
        e = libReqMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibRequirements();
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
//            e.setReqName(json.getString("re_name"));
            e.setCode(json.getString("code"));
            //e.setCreater(form.getCreater());
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
            if(libReqMapper.findByName(e.getReqName()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("需求名称已经存在");
                return voRes;
            }
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        e.setUpdater(form.getUpdater());
        e.setName(json.getString("name"));
        if (WzStrUtil.isNotBlank(json.getString("re_name"))) {
            e.setReqName(json.getString("re_name"));
        }
        e.setAddress(json.getString("address"));
        e.setCountry(json.getString("country"));
        e.setFzname(json.getString("fzname"));
        e.setFzzw(json.getString("fzzw"));
        e.setFzemail(json.getString("fzemail"));
        e.setFzphone(json.getString("fzphone"));
        e.setFzname2(json.getString("fzname2"));
        e.setFzzw2(json.getString("fzzw2"));
        e.setFzemail2(json.getString("fzemail2"));
        e.setFzphone2(json.getString("fzphone2"));
        e.setDomain(json.getString("domain"));
        e.setDomainOther(json.getString("domainOther"));
        e.setReqBack(json.getString("reqBack"));
        e.setReqBackOther(json.getString("reqBackOther"));
        e.setReqGet(json.getString("reqGet"));
        e.setReqDesc(json.getString("reqDesc"));
        e.setReqNew(json.getString("reqNew"));
        e.setReqOther(json.getString("reqOther"));
        e.setSearchParam(json.getString("search_param"));
        this.saveOrUpdate(e);
        this.saveLibReqOrResImage(json, e.getId());
        return voRes;
    }

    private VoResponse saveFormHisToRes(BusUserForm form, JSONObject json) {
        VoResponse voRes = new VoResponse();
        LibResults e = null;
        e = libResMapper.findByFormId(form.getId());
        if(e == null) {
            e = new LibResults();
            e.setUserId(form.getUserId());
            e.setFormId(form.getId());
//            e.setResName(json.getString("re_name"));
            e.setCode(json.getString("code"));
            //e.setCreater(form.getCreater());
            e.setCreater(form.getChecker());
            e.setNumber(form.getNumber());
            if(libResMapper.findByName(form.getReName()) != null) {
                voRes.setFail(voRes);
                voRes.setMessage("成果名称已经存在");
                return voRes;
            }
        }
        if (WzStrUtil.isBlank(e.getNumber())) {
            e.setNumber(form.getNumber());
        }
        if (WzStrUtil.isBlank(e.getUserId())) {
            e.setUserId(form.getUserId());
        }
        if (WzStrUtil.isNotBlank(json.getString("re_name"))) {
            e.setResName(json.getString("re_name"));
        }

        e.setUpdater(form.getUpdater());
        e.setName(json.getString("name"));
        e.setAddress(json.getString("address"));
        e.setCountry(json.getString("country"));
        e.setFzname(json.getString("fzname"));
        e.setFzemail(json.getString("fzemail"));
        e.setFzphone(json.getString("fzphone"));
        e.setFzname2(json.getString("fzname2"));
        e.setFzemail2(json.getString("fzemail2"));
        e.setFzphone2(json.getString("fzphone2"));
        e.setDomain(json.getString("domain"));
        e.setDomainOther(json.getString("domainOther"));
        e.setStage(json.getString("stage"));
        e.setCooperation(json.getString("cooperation"));
        e.setResDesc(json.getString("resDesc"));
        e.setUseArea(json.getString("applyLY"));
        e.setNewIdea(json.getString("newIdea"));
        e.setSqPatent(json.getString("sqPatent"));
        e.setHavePatent(json.getString("havePatent"));
        e.setOtherPatent(json.getString("otherPatent"));
        e.setPatents(json.getString("patents"));
        e.setSearchParam(json.getString("search_param"));
        this.saveOrUpdate(e);
        this.saveLibReqOrResImage(json, e.getId());
        return voRes;
    }

    boolean saveLibReqOrResImage(JSONObject json, String libId){
        LibImage imgs = new LibImage();
        imgs.setCreater(getUserName());

//        imgs.setField2(json.getString("picOrgLicense"));//营业执照
//        imgs.setField3(json.getString("picLpLicense"));//事业单位法人证书副本
//        imgs.setField4(json.getString("picLpIdCardFront"));//负责人身份证正面
//        imgs.setField5(json.getString("picLpIdCardBack"));//负责人身份证背面
//        imgs.setField6(json.getString("picLpIdCardInHand"));//负责人身份证手持
//        imgs.setField10(json.getString("picCommitmentLetter"));//需求成果发布承诺书
        try {
            imgs.setField1(this.getImageName(json, "picLogo"));
            imgs.setField2(this.getImageName(json, "picOrgLicense"));
            imgs.setField3(this.getImageName(json, "picLpLicense"));
            imgs.setField4(this.getImageName(json, "picLpIdCardFront"));
            imgs.setField5(this.getImageName(json, "picLpIdCardBack"));
            imgs.setField6(this.getImageName(json, "picLpIdCardInHand"));
            imgs.setField10(this.getImageName(json, "picCommitmentLetter"));
        }catch (Exception ex) {
            ex.printStackTrace();
            imgs.setField1(json.getString("picLogo"));
            imgs.setField2(json.getString("picOrgLicense"));//营业执照
            imgs.setField3(json.getString("picLpLicense"));//事业单位法人证书副本
            imgs.setField4(json.getString("picLpIdCardFront"));//负责人身份证正面
            imgs.setField5(json.getString("picLpIdCardBack"));//负责人身份证背面
            imgs.setField6(json.getString("picLpIdCardInHand"));//负责人身份证手持
            imgs.setField10(json.getString("picCommitmentLetter"));//需求成果发布承诺书
        }
        imgs.setLibId(libId);
        libImageService.saveOrUpdate(imgs);
        return true;
    }

    /**
     * 表格数据保存到对应的资源库中
     * @param form
     * @param json
     * @return
     */
    VoResponse saveFormHisToLib(BusUserForm form, JSONObject json) {
        VoResponse voRes = null;
        if(form.getFormType() == UserTypeEnum.Expert.key()) {
            voRes = this.saveFormHisToExpert(form, json);
            
        } else if(form.getFormType() == UserTypeEnum.Enterprise.key()) {//userType=2
            voRes = this.saveFormHisToEnterprise(form, json);
            
        }else if(form.getFormType() == UserTypeEnum.Service.key()) {
            voRes = this.saveFormHisToServices(form, json);
            
        }else if(form.getFormType() == UserTypeEnum.College.key()) {
            voRes = this.saveFormHisToCollege(form, json);
            
        }else if(form.getFormType() == UserTypeEnum.Requirement.key()) {
            voRes = this.saveFormHisToReq(form, json);
            
        }else if(form.getFormType() == UserTypeEnum.Results.key()) {
            voRes = this.saveFormHisToRes(form, json);
            
        }
        return voRes;
    }
    
    @Override
    public VoResponse rejectUserDetail(String id, String info) {
        VoResponse voRes = new VoResponse();
        BusUserForm form = busUserFormHisMapper.findById(id);
        if(form == null) {
            voRes.setNull(voRes);
            voRes.setMessage("数据异常");
            return voRes;
        }
        if(form.getCheckStatus() != 0) {
            voRes.setFail(voRes);
            voRes.setMessage("状态异常");
            return voRes;
        }
        BusUserCheck e = new BusUserCheck();
        e.setCheckStatus(2);
        e.setChecker(getUserName());
        e.setInfo(info);
        e.setFormId(id);
        int result = busUserCheckMapper.insert(e);
        if(result > 0) {
            result = busUserFormHisMapper.updateCheck(2, id);
        }
        return voRes;
    }

    @Transactional
    @Override
    public VoResponse checkUserDetail(String id) {
        VoResponse voRes = new VoResponse();
        int result = 0;
        BusUserForm form = busUserFormHisMapper.findById(id);
        User user = this.getUser();
        if(form == null) {
            voRes.setNull(voRes);
            voRes.setMessage("数据异常");
        }else if(form.getCheckStatus() == 0 || form.getCheckStatus() == 1){
            JSONObject json = null;
            try {
                json = JSON.parseObject(form.getDetail());
            }catch (Exception e) {
                e.printStackTrace();
                voRes.setFail(voRes);
                voRes.setMessage("表格数据异常");
                return voRes;
            }
            //转移form数据到资源库
            form.setUpdater(user.getUserName());
            form.setChecker(user.getUserName());
            voRes = this.saveFormHisToLib(form, json);
            if(!voRes.getSuccess()) {
                return voRes;
            }

            //新增审核信息
            BusUserCheck e = new BusUserCheck();
            e.setChecker(user.getUserName());
            e.setCheckStatus(1);
            e.setFormId(form.getId());
            busUserCheckMapper.insert(e);
            //修改用户表
            BusUser busUser = busUserMapper.findById(form.getUserId());
            if(busUser != null && busUser.getCheckStatus() == 1) {
                busUser.setCheckStatus(2);
                busUser.setCountry(json.getString("country"));//所在地区
                busUser.setAddress(json.getString("address"));//通讯地址
                busUserMapper.update(busUser);
            }

            /**
             * 修改名称和编码
             */
            if(busUser == null){
                busUser = busUserMapper.findByNameAndCode(form.getName(), form.getCode());
            }
            // 同步姓名和编码到用户
            if(busUser != null){
                busUser.setName(form.getNameAlias());
                busUser.setCode(form.getCodeAlias());
                busUserMapper.update(busUser);
            }
            // 更新form名称和编码
            form.setName(form.getNameAlias());
            form.setCode(form.getCodeAlias());
            busUserFormHisMapper.update(form);

            //修改表格审核状态
            result = busUserFormHisMapper.updateCheck(1, id);
            if(result <= 0) {
                voRes.setFail(voRes);
                voRes.setMessage("修改审核状态失败");
            }
        }
        return voRes;
    }
    
    @Override
    public VoResponse checkUserDetail(List<String> ids) {
        VoResponse voRes = null;
        int count = 1;
        for(String id : ids) {
            voRes = this.checkUserDetail(id);
            if(!voRes.getSuccess()) {
                if(ids.size() > 1) {
                    voRes.setMessage("第" + count + "条数据审核失败：" + voRes.getMessage());
                }
                return voRes;
            }
            count ++;
        }
        return voRes;
    }
    
    /**
     * 设置查询权限
     * @param lib
     */
    void setVoQuery(VoQuery lib) {
        User user = this.getUser();
        if(lib.getCheckStatus().equals("-1")) {//草稿
            lib.setUserId(user.getUserId());
            return;
        }
        if (0 != user.getUserType() && 101 != user.getUserType()) {
            lib.setUserId(user.getUserId());
        }
    }

    @Override
    public VoResponse getExpertPageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        //-1草稿，0待审核，1已发布，2驳回
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            if(lib.getCheckStatus().equals("1") ) {
                Page<LibExpert> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libExpertMapper.findByCondition(lib);
                PageInfo<LibExpert> info = new PageInfo<LibExpert>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("1");
                List<BusUserForm> list = busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
            }
            
        } else {
            voRes.setFail(voRes);
            voRes.setMessage("非法状态");
        }
        return voRes;
    }

    @Override
    public VoResponse getCollegePageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            if(lib.getCheckStatus().equals("1") ) {
                
                Page<LibCollege> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libCollegeMapper.findByCondition(lib);
                PageInfo<LibCollege> info = new PageInfo<LibCollege>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("4");
                List<BusUserForm> list = busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
                
            }
        }
        return voRes;
    }

    @Override
    public VoResponse getEnterprisePageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            
            if(lib.getCheckStatus().equals("1") ) {
                
                Page<LibEnterprise> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libEnterpriseMapper.findByCondition(lib);
                PageInfo<LibEnterprise> info = new PageInfo<LibEnterprise>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("2");
                busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
                
            }
        }
        return voRes;
    }

    @Override
    public VoResponse getServicePageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            
            if(lib.getCheckStatus().equals("1") ) {
                
                Page<LibServices> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libServiceMapper.findByCondition(lib);
                PageInfo<LibServices> info = new PageInfo<LibServices>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("3");
                busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
            }
        }
        
        return voRes;
    }
    
    @Override
    public VoResponse getResultsPageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            
            if(lib.getCheckStatus().equals("1") ) {
                
                Page<LibResults> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libResMapper.findByCondition(lib);
                PageInfo<LibResults> info = new PageInfo<LibResults>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("6");
                busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
            }
        }
        
        return voRes;
    }
    
    @Override
    public VoResponse getRequirementPageByCondition(VoQuery lib, int pageNum, int pageSize, String orderBy) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("登录超时，请重新登录");
            return voRes;
        }
        if(!StringUtils.isEmpty(lib.getCheckStatus())) {
            this.setVoQuery(lib);
            
            if(lib.getCheckStatus().equals("1") ) {
                
                Page<LibRequirements> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                libReqMapper.findByCondition(lib);
                PageInfo<LibRequirements> info = new PageInfo<LibRequirements>(page);
                voRes.setData(info);
                
            }else {
                Page<BusUserForm> page = PageHelper.startPage(pageNum, pageSize);
                if(StringUtils.isEmpty(orderBy)) {
                    PageHelper.orderBy("f.create_time desc");
                }else {
                    PageHelper.orderBy(orderBy);
                }
                lib.setUserType("7");
                busUserFormHisMapper.findByFromType(lib);
                PageInfo<BusUserForm> info = new PageInfo<BusUserForm>(page);
                voRes.setData(info);
            }
        }
        
        return voRes;
    }

    @Override
    public Object getLibsByUser(int userType, String name, String code) {
        switch(userType) {
        case 1 : 
            LibExpert expert = libExpertMapper.findByNameAndCode(name, code);
            return expert;
        case 2 : 
            LibEnterprise enterprise = libEnterpriseMapper.findByNameAndCode(name, code);
            return enterprise;
        case 3 : 
            LibServices services = libServiceMapper.findByNameAndCode(name, code);
            return services;
        case 4 : 
            LibCollege college = libCollegeMapper.findByNameAndCode(name, code);
            return college;
        default:
            return null;
        }
    }
    
    @Override
    public VoResponse getLibsByUser() {
        VoResponse voRes = new VoResponse();
        User user = this.getUser();
        if (null == user) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或已超时，请重新登录");
            return voRes;
        }
        if(user != null) {
            BusUser busUser = busUserMapper.findById(user.getUserId());
            if (null == user) {
                voRes.setFail(voRes);
                voRes.setMessage("未发现该用户");
                return voRes;
            }
            if(busUser != null) {
                voRes.setData(this.getLibsByUser(busUser.getUserType(), busUser.getName(), busUser.getCode()));
                if (null == voRes.getData()) {
                    User userModel = getUser();
                    Map<String,Object> map = new HashMap<>();
                    map.put("detail",JSONObject.toJSONString(userModel));
                    voRes.setData(map);
//                    voRes.setFail(voRes);
//                    voRes.setMessage("请先完善用户信息");
                }
            }
        }
        return voRes;
    }

    @Override
    public List<VoTaskSum> taskDoing() {
        User user = this.getUser();
        List<VoTaskSum> list = busUserFormHisMapper.findSubmitLib(user.getUserId());
        return list;
    }

    @Override
    public List<VoTaskSum> taskDoingSum() {
        User u = getUser();
        List<VoTaskSum> list = busUserFormHisMapper.findGroupByFromType(0);
        return list;
    }

    @Override
    public List<VoTaskSum> taskDjFromerDoingSum() {
        User u = getUser();
        List<VoTaskSum> fromerList = dataStatisticsMapper.findMeetingFromer(u.getUserId());
        return fromerList;
    }

    @Override
    public List<VoTaskSum> taskDjTargeterDoingSum() {
        User u = getUser();
        List<VoTaskSum> targetList = dataStatisticsMapper.findMeetingTargeter(u.getUserId());
        return targetList;
    }

    @Override
    public VoResponse updateLibStatus(String id, int type, int status) {
        VoResponse voRes = new VoResponse();
        int result = 0;
        switch(type) {
        case 1 :
            result = libExpertMapper.updateStatus(id, status); break;
        case 2 :
            result = libEnterpriseMapper.updateStatus(id, status); break;
        case 3 :
            result = libServiceMapper.updateStatus(id, status); break;
        case 4 :
            result = libCollegeMapper.updateStatus(id, status); break;
        case 6 :
            result = libResMapper.updateStatus(id, status); break;
        case 7 :
            result = libReqMapper.updateStatus(id, status); break;
        }
        if(result != 1) {
            voRes.setFail(voRes);
            voRes.setMessage("参数错误");
        }
        return voRes;
    }
    
    @Override
    public VoResponse updateLibCreditLevel(String id, int type, int creditLevel) {
        VoResponse voRes = new VoResponse();
        int result = 0;
        switch(type) {
        case 1 :
            result = libExpertMapper.updateCreditLevel(id, creditLevel); break;
        case 2 :
            result = libEnterpriseMapper.updateCreditLevel(id, creditLevel); break;
        case 3 :
            result = libServiceMapper.updateCreditLevel(id, creditLevel); break;
        case 4 :
            result = libCollegeMapper.updateCreditLevel(id, creditLevel); break;
        }
        if(result != 1) {
            voRes.setFail(voRes);
            voRes.setMessage("参数错误");
        }
        return voRes;
    }

    @Override
    public VoResponse offUserDetail(List<String> ids, int type) {
        VoResponse voRes = null;
        int count = 0;
        for(String id : ids) {
            voRes = this.updateLibStatus(id, type, 0);
            if(!voRes.getSuccess()) {
                if(ids.size() > 1) {
                    voRes.setMessage("第" + count + "条数据下架失败：" + voRes.getMessage());
                }
                return voRes;
            }
            count ++;
        }
        return voRes;
    }

    @Override
    public List<BusUserCheck> getCheckInfo(String formId) {
        List<BusUserCheck> list = busUserCheckMapper.findByFormId(formId);
        return list;
    }
    
    int saveOrUpdate(LibRequirements e) {
        int result;
        if(e.getId() == null) {
            result = libReqMapper.insert(e);
        }else {
            result = libReqMapper.update(e);
        }
        return result;
    }
    
    int saveOrUpdate(LibResults e) {
        int result;
        if(e.getId() == null) {
            result = libResMapper.insert(e);
        }else {
            result = libResMapper.update(e);
        }
        return result;
    }

    @Override
    public VoResponse publishRe(BusUserForm form) {
        VoResponse voRes = new VoResponse();
        
        JSONObject json = null;
        try {
            json = JSON.parseObject(form.getDetail());
        }catch (Exception e) {
            e.printStackTrace();
            voRes.setFail(voRes);
            voRes.setMessage("表格数据异常");
            return voRes;
        }
        form.setName(json.getString("name"));//企业名称
        form.setCode(json.getString("code"));//企业信用码
        form.setReName(json.getString("re_name"));//需求成果名称
        User user = this.getUser();
        int result = 0;
        if(form.getCheckStatus() == CheckStatusEnum.Checking.value()) {//提交
            //判断用户发布权限
            if(user.getCheckStatus() != 2) {
                LibImage image = libImageService.getUserImage("");
                if(image == null) {
                    voRes.setFail(voRes);
                    voRes.setMessage("请上传对应的营业执照照片或事业单位的照片；");
                    return voRes;
                }
            }
        }
        if(form.getId() == null) {
            if(!this.setResCode(form, UserTypeEnum.getTheCode(form.getFormType()))) {
                voRes.setFail(voRes);
                voRes.setMessage("获取编码异常；请联系管理员");
                return voRes;
            }
            form.setCreater(user.getUserName());
            result = busUserFormHisMapper.insert(form);
        }else {
            form.setUpdater(user.getUserName());
            result = busUserFormHisMapper.update(form);
        }
        voRes.setData(result);
        return voRes;
    }

    @Override
    public VoResponse exportLib(VoQuery lib, OutputStream out) {
        VoResponse voRes = new VoResponse();
        int type = 0;
        if(lib.getUserType() == null) {
            voRes.setFail(voRes);
            voRes.setMessage("参数类型不能为空");
            return voRes;
        }
        User u = getUser(lib.getTokenStr());
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或登录已超时");
            return voRes;
        }
        type = Integer.parseInt(lib.getUserType());
        BusUserForm form = this.getUserForm(type);
        if(type == UserTypeEnum.Expert.key()) {
            List<LibExpert> list = libExpertMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的专家信息");
                return voRes;
            }
            ExcelUtil.writeExpertExcel(list, form.getDetail(), out);
            
        }else if(type == UserTypeEnum.Enterprise.key()) {
            List<LibEnterprise> list = libEnterpriseMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的企业信息");
                return voRes;
            }
            ExcelUtil.writeEnterpriseExcel(list, form.getDetail(), out);
            
        }else if(type == UserTypeEnum.Service.key()) {
            List<LibServices> list = libServiceMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的服务机构信息");
                return voRes;
            }
            ExcelUtil.writeServiceExcel(list, form.getDetail(), out);
            
        }else if(type == UserTypeEnum.College.key()) {
            List<LibCollege> list = libCollegeMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的高校院所信息");
                return voRes;
            }
            if (null == form) {
                ExcelUtil.writeCollegeExcel(list, "", out);
            } else {
                ExcelUtil.writeCollegeExcel(list, form.getDetail(), out);
            }
        }else if(type == UserTypeEnum.Results.key()) {
            List<LibResults> list = libResMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的成果信息");
                return voRes;
            }
            ExcelUtil.writeResExcel(list, form.getDetail(), out);
            
        }else if(type == UserTypeEnum.Requirement.key()) {
            List<LibRequirements> list = libReqMapper.findByCondition(lib);
            if (null == list || 0 == list.size()) {
                voRes.setFail(voRes);
                voRes.setMessage("未查询到待导出的需求信息");
                return voRes;
            }
            ExcelUtil.writeReqExcel(list, form.getDetail(), out);
            
        }else {
            voRes.setFail(voRes);
            voRes.setMessage("参数错误");
            return voRes;
        }
        return null;
    }

}
